package main

import (
	"github.com/xgdapg/wtk"
	"math"
	"strconv"
)

type IndexHandler struct {
	wtk.Handler
}

func (this *IndexHandler) Get() {
	page := 1
	strPage := this.Context.GetPathVar("Page")
	if strPage != "" {
		page, _ = strconv.Atoi(strPage)
	}
	if page < 1 {
		page = 1
	}

	list, err := model.GetPosts(page)
	if err != nil {
		this.Context.Abort(500, "")
		return
	}
	if len(list) == 0 && page != 1 {
		this.Context.NotFound()
		return
	}
	totalCnt, err := model.GetPostsCnt()
	if err != nil {
		this.Context.Abort(500, "")
		return
	}

	maxPage := int(math.Ceil(float64(totalCnt) / float64(cfg.NumPerPage)))
	prev := page - 1
	next := page + 1
	if next > maxPage {
		next = 0
	}

	this.Template.SetVar("PageType", "index")
	this.Template.SetVar("PostList", list)
	this.Template.SetVar("CurrPage", page)
	this.Template.SetVar("PrevPage", prev)
	this.Template.SetVar("NextPage", next)
	this.Template.SetVar("MaxPage", maxPage)
	this.Template.SetTemplateFile(cfg.ThemeTplPath() + "/wrap.tpl")
	this.Template.SetSubTemplateFile("content", cfg.ThemeTplPath()+"/posts.tpl")
}

type PostHandler struct {
	wtk.Handler
}

func (this *PostHandler) Get() {
	pid, _ := strconv.Atoi(this.Context.GetPathVar("PostId"))

	data, _ := model.GetPostById(pid)
	if data == nil {
		this.Context.NotFound()
		return
	}

	this.Template.SetVar("PageType", "post")
	this.Template.SetVar("Post", data)
	this.Template.SetTemplateFile(cfg.ThemeTplPath() + "/wrap.tpl")
	this.Template.SetSubTemplateFile("content", cfg.ThemeTplPath()+"/post.tpl")
}

type TagHandler struct {
	wtk.Handler
}

func (this *TagHandler) Get() {
	page := 1
	tagName := this.Context.GetPathVar("TagName")
	strPage := this.Context.GetPathVar("Page")
	if strPage != "" {
		page, _ = strconv.Atoi(strPage)
	}

	list, _ := model.GetPostsByTag(tagName, page)
	totalCnt, _ := model.GetPostsCntByTag(tagName)
	if len(list) == 0 {
		this.Context.NotFound()
		return
	}

	maxPage := int(math.Ceil(float64(totalCnt) / float64(cfg.NumPerPage)))
	prev := page - 1
	next := page + 1
	if next > maxPage {
		next = 0
	}

	this.Template.SetVar("PageType", "tag")
	this.Template.SetVar("PostList", list)
	this.Template.SetVar("CurrPage", page)
	this.Template.SetVar("PrevPage", prev)
	this.Template.SetVar("NextPage", next)
	this.Template.SetVar("MaxPage", maxPage)
	this.Template.SetTemplateFile(cfg.ThemeTplPath() + "/wrap.tpl")
	this.Template.SetSubTemplateFile("content", cfg.ThemeTplPath()+"/posts.tpl")
}
